import requests
import time
import random

get_headers = {
    'accept': '*/*',
    'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
    'content-type': 'application/json; charset=UTF-8',
    'origin': 'https://blog.csdn.net',
    'priority': 'u=1, i',
    'Cookie': '填入cookie',
    'referer': 'https://blog.csdn.net/m0_48405781/article/details/125034475',
    'sec-ch-ua': '"Microsoft Edge";v="131", "Chromium";v="131", "Not_A Brand";v="24"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"macOS"',
    'sec-fetch-dest': 'empty',
    'sec-fetch-mode': 'cors',
    'sec-fetch-site': 'same-site',
    'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0'
}

post_headers = {
    'Accept': 'application/json, text/javascript, */*; q=0.01',
    'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
    'Connection': 'keep-alive',
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'Origin': 'https://blog.csdn.net',
    'Cookie': '填入cookie',
    'Referer': 'https://blog.csdn.net/tangPHP/article/details/145437695',
    'Sec-Fetch-Dest': 'empty',
    'Sec-Fetch-Mode': 'cors',
    'Sec-Fetch-Site': 'same-origin',
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0',
    'X-Requested-With': 'XMLHttpRequest',
    'sec-ch-ua': '"Microsoft Edge";v="131", "Chromium";v="131", "Not_A Brand";v="24"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': 'macOS'
}


def follow_user(username, follow, source, from_type, detail_source_name, source_id):
    """
    关注用户
    """
    url = 'https://mp-action.csdn.net/interact/wrapper/pc/fans/v1/api/follow'

    data = {
        'username': username,
        'follow': follow,
        'source': source,
        'fromType': from_type,
        'detailSourceName': detail_source_name,
        'sourceId': source_id
    }

    response = requests.post(url, headers=get_headers, json=data)

    if response.status_code == 200:
        data = response.json()
        print(data)
        if data['code'] != 200:
            # 如果已经关注了就不评论了
            return 0
    else:
        print(f"请求失败，状态码: {response.status_code}")


def submit_comment(article_id, content, comment_id=None):
    """
    提交评论
    """
    url = 'https://blog.csdn.net/phoenix/web/v1/comment/submit'

    data = {
        'commentId': comment_id,
        'content': content,
        'articleId': article_id
    }

    response = requests.post(url, headers=post_headers, data=data)

    if response.status_code == 200:
        data = response.json()
        print(data)
        if data['code'] != 200:
            return 0
    else:
        print(f"请求失败，状态码: {response.status_code}")


def fetch_recommendations():
    url = 'https://cms-api.csdn.net/v1/web_home/select_content?componentIds=www-blog-recommend'

    response = requests.get(url, headers=get_headers)

    if response.status_code == 200:
        data = response.json()
        return data['data']['www-blog-recommend']['info']
    else:
        print(f"请求失败，状态码: {response.status_code}")
        return []


def pause_random_time(min_seconds, max_seconds):
    # 生成一个在 min_seconds 和 max_seconds 之间的随机时间
    random_seconds = random.uniform(min_seconds, max_seconds)
    print(f"程序将暂停 {random_seconds:.2f} 秒")
    time.sleep(random_seconds)


if __name__ == '__main__':
    while True:
        # 拿取最新发布的文章id list 和作者 list。这里状态可能维护在服务端，不对用户暴露，因此不断访问该接口即可
        recommendations = fetch_recommendations()
        contents = ['您的文章真是精辟入里，让我受益匪浅，感谢您的精彩分享！期待与您相互关注。',
                    '大佬写得太好了，收获满满，感谢大佬的分享！也欢迎您互关~~',
                    '大神的内容总是那么有深度，读完感觉又提升了一个层次，谢谢你的分享，欢迎互关哦',
                    '非常感谢您的慷慨分享，也欢迎您互关']

        for item in recommendations:
            extend = item['extend']
            print(f"product_id: {extend['product_id']}")
            print(f"title: {extend['title']}")
            print(f"user_name: {extend['user_name']}")
            print(f"url: {extend['url']}")

            # 关注用户并且评论
            has_follow = follow_user(
                username='sekever',
                follow=extend['user_name'],
                source='BLOG_DETAIL',
                from_type='pc',
                detail_source_name=extend['title'],
                source_id=extend['product_id']
            )
            print(f"has_follow: {has_follow}")
            if has_follow != 0:
                has_fail = submit_comment(
                    article_id=extend['product_id'],
                    content=contents[random.randint(0, 3)]
                )
                if has_fail == 0:
                    break

            # 暂停一个随机时间
            pause_random_time(15, 20)
            print("暂停结束，程序继续执行")
